from rest_framework.viewsets import GenericViewSet, ModelViewSet, ViewSet

from stall.models import Stall, Zone, Region, Food, Part, Bill, Row
from user.models import User
from stall.serializers import StallShowSerializer, ZoneShowSerializer, GetRegionSerializer, FoodShowSerializer
from stall.serializers import PartShowSerializer, StallNumChoseSerializer, CreateStallSerializer
from stall.serializers import RegionShowSerializer, GetStallSerializer, CreateFoodSerializer
from stall.serializers import UpdateFoodSerializer, GetBillSerializer
from fooder_drf.utils.responses import CommonResponse


class StallShowView(GenericViewSet):
    queryset = Stall.objects.all()
    serializer_class = StallShowSerializer

    def get_stalls(self, request, *args, **kwargs):
        region_id = int(request.query_params.get('region_id'))
        zone_id = int(request.query_params.get('zone_id'))
        ordering_field = request.query_params.get('ordering')
        stall_list = self.get_queryset()
        stall_ser = self.get_serializer(instance=stall_list, many=True)
        data_list = stall_ser.data
        return_list = []
        for data in data_list:
            if data.get('region_id') == region_id and data.get('zone_id') == zone_id:
                return_list.append(data)
        if ordering_field:
            return_list = sorted(return_list, key=lambda x: x.get(ordering_field), reverse=True)
        return CommonResponse(tip='食摊展示', data=return_list)


class ZoneShowView(GenericViewSet):
    queryset = Zone.objects.all()
    serializer_class = ZoneShowSerializer

    def get_zones(self, request, *args, **kwargs):
        region_id = int(request.query_params.get('region_id'))
        ordering_field = request.query_params.get('ordering')
        zone_list = self.get_queryset()
        zone_ser = self.get_serializer(instance=zone_list, many=True)
        data_list = zone_ser.data
        return_list = []
        for data in data_list:
            if data.get('region_id') == region_id:
                return_list.append(data)
        if ordering_field:
            return_list = sorted(return_list, key=lambda x: x.get('sales').get(ordering_field), reverse=True)
        return CommonResponse(tip='食区展示', data=return_list)


class GetRegionView(GenericViewSet):
    queryset = Region.objects.all()
    serializer_class = GetRegionSerializer

    def get_region(self, request, *args, **kwargs):
        region_id = int(request.query_params.get('region_id'))
        region_list = self.get_queryset()
        region_mol = region_list.filter(region_id=region_id).first()
        region_ser = self.get_serializer(instance=region_mol)
        return CommonResponse(tip='获取城区信息', data=region_ser.data)


class FoodShowView(GenericViewSet):
    queryset = Food.objects.all()
    serializer_class = FoodShowSerializer

    def get_foods(self, request, *args, **kwargs):
        stall_id = request.query_params.get('stall_id')
        sort_field = request.query_params.get('sort_field')
        food_list = self.get_queryset()
        food_ser = self.get_serializer(instance=food_list, many=True)
        data_list = food_ser.data
        return_list = []
        for data in data_list:
            if data.get('stall_id') == stall_id:
                return_list.append(data)
        return_list = sorted(return_list, key=lambda x: x.get('month_sales'), reverse=True)
        if sort_field:
            return_list_2 = []
            for data in return_list:
                if data.get('sort') == sort_field:
                    return_list_2.append(data)
            return_list = return_list_2
        return CommonResponse(tip='小吃展示', data=return_list)


class PartShowView(GenericViewSet):
    queryset = Part.objects.all()
    serializer_class = PartShowSerializer

    def get_parts(self, request, *args, **kwargs):
        stall_id = request.query_params.get('stall_id')
        sort_field = request.query_params.get('sort_field')
        part_list = self.get_queryset()
        part_ser = self.get_serializer(instance=part_list, many=True)
        data_list = part_ser.data
        return_list = []
        for data in data_list:
            if data.get('stall_id') == stall_id and data.get('sort') == sort_field:
                return_list.append(data)
        return_list = sorted(return_list, key=lambda x: x.get('order'))
        return CommonResponse(tip='配件展示', data=return_list)


class StallNumChoseView(GenericViewSet):
    queryset = Stall.objects.all()
    serializer_class = StallNumChoseSerializer

    def get_stall_nums(self, request, *args, **kwargs):
        region_id = request.query_params.get('region_id')
        zone_id = request.query_params.get('zone_id')
        stall_list = self.get_queryset()
        stall_ser = self.get_serializer(instance=stall_list, many=True)
        chose_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16']
        for stall in stall_ser.data:
            if stall.get('region_id') == region_id and stall.get('zone_id') == zone_id:
                chose_list.remove(stall.get('order_id'))
        options = []
        for value in chose_list:
            options.append({'value': value, 'label': '{}号摊位'.format(value)})
        return CommonResponse(tip='获取可选摊位编号', data=options)


class CreateStallView(ViewSet):
    def create_stall(self, request, *args, **kwargs):
        stall_ser = CreateStallSerializer(data=request.data)
        if stall_ser.is_valid():
            stall_ser.save()
            return CommonResponse(tip='食摊已创建')
        else:
            error = stall_ser.errors.get('non_field_errors')[0]
            return CommonResponse(state=0, tip='食摊创建失败', error=error)


class RegionShowView(GenericViewSet):
    queryset = Region.objects.all()
    serializer_class = RegionShowSerializer

    def get_regions(self, request, *args, **kwargs):
        ordering_field = request.query_params.get('ordering')
        region_list = self.get_queryset()
        region_ser = self.get_serializer(instance=region_list, many=True)
        return_list = region_ser.data
        if ordering_field:
            return_list = sorted(return_list, key=lambda x: x.get('sales').get(ordering_field), reverse=True)
        return CommonResponse(tip='城区展示', data=return_list)


class GetStallView(ViewSet):
    def get_stall(self, request, *args, **kwargs):
        username = request.data.get('username')
        user = User.objects.filter(username=username).first()
        user_id = user.id
        stall = Stall.objects.filter(user_id=user_id).first()
        stall_ser = GetStallSerializer(instance=stall)
        return CommonResponse(tip='获取摊位信息', data=stall_ser.data)


class ChangeStallStateView(ViewSet):
    def change_stall_state(self, request, *args, **kwargs):
        new_state = request.data.get('stall_state')
        stall_id = request.data.get('stall_id')
        stall = Stall.objects.filter(id=stall_id).first()
        stall.state = new_state
        stall.save()
        return CommonResponse(tip='修改摊位状态成功')


class CreateFoodView(ViewSet):
    def create_food(self, request, *args, **kwargs):
        food_ser = CreateFoodSerializer(data=request.data)
        if food_ser.is_valid():
            return CommonResponse(tip='添加小吃成功')
        else:
            error = food_ser.errors.get('non_field_errors')[0]
            return CommonResponse(state=0, tip='添加小吃失败', error=error)


class UpdateFoodView(ViewSet):
    def update_food(self, request, *args, **kwargs):
        food_ser = UpdateFoodSerializer(data=request.data)
        if food_ser.is_valid():
            return CommonResponse(tip='修改小吃成功')
        else:
            error = food_ser.errors.get('non_field_errors')[0]
            return CommonResponse(state=0, tip='修改小吃失败', error=error)


class DelFoodView(ViewSet):
    def del_food(self, request, *args, **kwargs):
        food_id = request.data.get('food_id')
        Food.objects.filter(id=food_id).delete()
        return CommonResponse(tip='删除小吃成功')


class CreateFoodSortView(ViewSet):
    def create_food_sort(self, request, *args, **kwargs):
        stall_id = request.data.get('stall_id')
        new_sort = request.data.get('new_sort')
        stall = Stall.objects.filter(id=stall_id).first()
        food_sort_list = stall.food_sort.split('$')
        food_sort_list.append(new_sort)
        new_food_sort = '$'.join(food_sort_list)
        stall.food_sort = new_food_sort
        stall.save()
        Food.objects.create(
            stall_id=stall_id,
            sort=new_sort,
            name='示例小吃',
            price=999,
            desc='示例小吃，请勿购买'
        )
        return CommonResponse(tip='新增小吃种类')


class UpdateFoodSortView(ViewSet):
    def update_food_sort(self, request, *args, **kwargs):
        stall_id = request.data.get('stall_id')
        old_sort = request.data.get('old_sort')
        new_sort = request.data.get('new_sort')
        stall = Stall.objects.filter(id=stall_id).first()
        food_sort = stall.food_sort
        new_food_sort = food_sort.replace(old_sort, new_sort)
        stall.food_sort = new_food_sort
        stall.save()
        Food.objects.filter(sort=old_sort).update(sort=new_sort)
        return CommonResponse(tip='修改小吃种类')


class DelFoodSortView(ViewSet):
    def del_food_sort(self, request, *args, **kwargs):
        stall_id = request.data.get('stall_id')
        del_sort = request.data.get('del_sort')
        stall = Stall.objects.filter(id=stall_id).first()
        Food.objects.filter(sort=del_sort).delete()
        food_sort_list = stall.food_sort.split('$')
        food_sort_list.remove(del_sort)
        new_food_sort = '$'.join(food_sort_list)
        stall.food_sort = new_food_sort
        stall.save()
        return CommonResponse(tip='删除小吃种类')


class GetBillView(ViewSet):
    def get_bill(self, request, *args, **kwargs):
        stall_id = request.query_params.get('stall_id')
        username = request.query_params.get('username')
        user = User.objects.filter(username=username).first()
        user_id = user.id
        bill = Bill.objects.filter(stall_id=stall_id, user_id=user_id).first()
        if not bill:
            Bill.objects.create(stall_id=stall_id, user_id=user_id)
            return CommonResponse(state=0, tip='新建账单')
        row = Row.objects.filter(bill_id=bill.id)
        if not row:
            return CommonResponse(state=0, tip='空账单')
        bill_ser = GetBillSerializer(instance=bill)
        return CommonResponse(tip='获取账单', data=bill_ser.data)


class AddFoodView(ViewSet):
    def add_food(self, request, *args, **kwargs):
        bill_id = request.data.get('bill_id')
        food_id = request.data.get('food_id')
        row = Row.objects.filter(bill_id=bill_id, food_id=food_id).first()
        if row:
            row.count += 1
            row.save()
        else:
            Row.objects.create(
                bill_id=bill_id,
                food_id=food_id
            )
        return CommonResponse(tip='小吃加入菜单成功')